from flask import Blueprint, request

from applications.utils.http import success_api, fail_api
import numpy as np
import io
import datetime
import os
import random

bp = Blueprint('index', __name__, url_prefix='/index')


@bp.get('/')
def index():


    return "hello world!"


@bp.get('/getVideo')
def get_video():
    return success_api(msg="成功", data={
        "webrtc": "/zl/index/api/webrtc?app=live&stream=test&type=play",
        "mp4": "/zl/live/test.live.mp4",
        "flv": "/zl/live/test.live.flv",
        "hls": "/zl/live/test/hls.m3u8",
    })


@bp.post('/receive_imu')
def receive_imu():
    # 从POST请求中获取列表数据
    try:
        # 从POST请求中直接获取字符串数据
        data = request.get_data(as_text=True)
        if not data:
            raise ValueError("未获取到有效的数据")
    except Exception as e:
        return fail_api(msg=f"接收数据失败: {str(e)}")

    # 打印数据
    print(data)
    # 获取当前时间并格式化为 yyyymmddhhmmssfff 格式
    current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]
    os.makedirs("imu_data", exist_ok=True)
    file_name = f"imu_data/{current_time}.txt"
    # 将data存储为txt文件
    try:
        with open(file_name, 'w') as f:
            f.write(data)
    except Exception as e:
        print(f"保存文件失败: {str(e)}")


    return success_api(msg="ok", data={
    })


@bp.get('/get_random_imu_data')
def get_random_imu_data():
    try:
        # 获取 imu_data 文件夹下所有的 txt 文件
        if not os.path.exists("imu_data"):
            return fail_api(msg="imu_data 文件夹不存在")
        txt_files = [f for f in os.listdir("imu_data") if f.endswith('.txt')]
        if not txt_files:
            return fail_api(msg="imu_data 文件夹下没有 txt 文件")

        # 随机选择一个文件
        file_name = os.path.join("imu_data", random.choice(txt_files))

        # 读取文件内容
        with open(file_name, 'r') as f:
            data = f.read()


        return success_api(msg="ok", data={})
    except Exception as e:
        return fail_api(msg=f"获取随机IMU数据失败: {str(e)}")


@bp.post('/receive_lidar')
def receive_lidar():
    # 从POST请求中获取列表数据
    try:
        # 获取请求的JSON数据
        data = request.get_json()
        if data is None:
            raise ValueError("未获取到有效的JSON数据")
        # 将列表转换为numpy数组
        arr = np.array(data)
    except Exception as e:
        return fail_api(msg=f"接收数据失败: {str(e)}")

    # 打印数组形状
    # print(arr.shape)
    # 打印数组元素
    # print(arr)
    # 获取当前时间并格式化为 yyyymmddhhmmssfff 格式
    current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]
    os.makedirs("lidar_data", exist_ok=True)
    file_name = f"lidar_data/{current_time}.txt"

    # 将arr存储为txt文件
    try:
        with open(file_name, 'w') as f:
            np.savetxt(f, arr, fmt='%s')
    except Exception as e:
        print(f"保存文件失败: {str(e)}")


    return success_api(msg="ok", data={
    })


@bp.get('/get_random_lidar_data')
def get_random_lidar_data():
    try:
        # 获取 lidar_data 文件夹下所有的 txt 文件
        if not os.path.exists("lidar_data"):
            return fail_api(msg="lidar_data 文件夹不存在")
        txt_files = [f for f in os.listdir("lidar_data") if f.endswith('.txt')]
        if not txt_files:
            return fail_api(msg="lidar_data 文件夹下没有 txt 文件")

        # 随机选择一个文件
        file_name = os.path.join("lidar_data", random.choice(txt_files))

        # 读取文件内容
        arr = np.loadtxt(file_name, dtype=str)


        return success_api(msg="ok", data={})
    except Exception as e:
        return fail_api(msg=f"获取随机激光雷达数据失败: {str(e)}")
